package com.lekang.service.impl;

import com.lekang.common.core.domain.entity.SysUser;
import com.lekang.domain.CaregiverBedBinding;
import com.lekang.mapper.CaregiverBedBindingMapper;
import com.lekang.mapper.ElderlyMapper;
import com.lekang.mapper.TaskArrangementMapper;
import com.lekang.service.ICaregiverBedService;

import com.lekang.system.mapper.SysUserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName ICaregiverBedServiceImpl
 * @Description TODO
 * @Author lxm
 * @Date 2025年10月20日 15:56
 * @Version 1.0
 */
@Service
public class ICaregiverBedServiceImpl implements ICaregiverBedService {
    private static final Logger log = LoggerFactory.getLogger(ICaregiverBedServiceImpl.class);

    @Autowired
    private CaregiverBedBindingMapper bindingMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private ElderlyMapper elderlyMapper;

    @Autowired
    private TaskArrangementMapper taskArrangementMapper;

    @Override
    public List<SysUser> getBoundCaregivers(Long bedId) {
        List<Long> userIds = bindingMapper.selectCaregiverIdsByBedId(bedId);
        System.out.println("中间表查询到的护理员ID：" + userIds); // 新增日志
        if (userIds.isEmpty()) {
            return new ArrayList<>();
        }
        List<SysUser> caregivers = sysUserMapper.selectUsersByIds(userIds.toArray(new Long[0]));
        System.out.println("查询到的护理员信息：" + caregivers); // 新增日志
        return caregivers;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void bindCaregiversToBed(Long bedId, List<Long> caregiverIds) {
        if(bedId == null){
            throw new IllegalArgumentException("床位ID不能为空");
        }
        
        log.info("开始为床位 {} 绑定护理员: {}", bedId, caregiverIds);
        
        // 1. 校验护理员唯一性（每个护理员只能绑定一个床位）
        if (caregiverIds != null && !caregiverIds.isEmpty()) {
            for (Long caregiverId : caregiverIds) {
                Long existingBedId = bindingMapper.selectBedIdByCaregiverId(caregiverId, bedId);
                if (existingBedId != null) {
                    // 查询护理员姓名
                    SysUser caregiver = sysUserMapper.selectUserById(caregiverId);
                    String caregiverName = caregiver != null ? caregiver.getNickName() : "ID:" + caregiverId;
                    
                    throw new RuntimeException(String.format("护理员【%s】已被床位 %d 绑定，不能重复绑定", 
                        caregiverName, existingBedId));
                }
            }
            log.info("护理员唯一性校验通过");
        }
        
        // 2. 删除原有绑定
        bindingMapper.deleteByBedId(bedId);
        
        // 3. 新增绑定（若有护理员ID）
        if (caregiverIds != null && !caregiverIds.isEmpty()) {
            List<CaregiverBedBinding> bindings = new ArrayList<>();
            for (Long userId : caregiverIds) {
                CaregiverBedBinding binding = new CaregiverBedBinding();
                binding.setBedId(bedId);
                binding.setCaregiverId(userId);
                bindings.add(binding);
            }
            bindingMapper.batchInsert(bindings);
            log.info("床位 {} 护理员绑定成功", bedId);
            
            // 3. 同步更新该床位下所有在住老人的待执行任务
            try {
                // 3.1 查询该床位下的所有在住老人ID
                List<Long> elderlyIds = elderlyMapper.selectElderlyIdsByBedId(bedId);
                
                if (elderlyIds != null && !elderlyIds.isEmpty()) {
                    log.info("床位 {} 下有 {} 位在住老人，开始同步任务护理员", bedId, elderlyIds.size());
                    
                    // 3.2 逐个更新每位老人的待执行任务，采用轮流分配策略
                    int totalUpdated = 0;
                    for (int i = 0; i < elderlyIds.size(); i++) {
                        Long elderlyId = elderlyIds.get(i);
                        // 轮流分配：使用索引取模
                        Long assignedCaregiverId = caregiverIds.get(i % caregiverIds.size());
                        
                        int updated = taskArrangementMapper.updateCaregiverForElderly(elderlyId, assignedCaregiverId);
                        totalUpdated += updated;
                        
                        log.debug("老人ID: {} 的 {} 条任务已分配给护理员ID: {}", elderlyId, updated, assignedCaregiverId);
                    }
                    
                    log.info("床位 {} 的待执行任务护理员同步完成，共更新 {} 条任务", bedId, totalUpdated);
                } else {
                    log.info("床位 {} 下暂无在住老人，无需同步任务", bedId);
                }
            } catch (Exception e) {
                log.error("同步床位 {} 的任务护理员失败", bedId, e);
                throw e; // 事务会回滚
            }
        } else {
            log.info("床位 {} 解绑所有护理员", bedId);
            
            // 如果解绑所有护理员，将该床位下老人的待执行任务的护理员ID设置为null
            List<Long> elderlyIds = elderlyMapper.selectElderlyIdsByBedId(bedId);
            if (elderlyIds != null && !elderlyIds.isEmpty()) {
                // 这里需要一个特殊的更新方法，将护理员ID设置为null
                // 暂时不实现，因为通常不会完全解绑所有护理员
                log.warn("床位 {} 解绑所有护理员，但任务的护理员字段未清空", bedId);
            }
        }
    }

    @Override
    public List<Long> getAllBoundCaregiverIds() {
        return bindingMapper.selectAllBoundCaregiverIds();
    }
}
